﻿/*
 * marqdown
 * --------
 * a C# Markdown processor
 * 
 * Copyright (c) 2010 Andrew Wall
 * http://code.google.com/p/marqdown/
 * 
 * 
 */


#region Copyright and license

/*

Copyright (c) 2010 Andrew Wall

 http://www.opensource.org/licenses/mit-license.php
  
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#endregion


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Marqdown
{
    namespace ToStringStrategies
    {
        public abstract class Strategy
        {
            public abstract void ToStringStrategy(List<String> aList, string prefix, StringBuilder contents);
        }
        class KeepNewLine : Strategy
        {
            public override void ToStringStrategy(List<String> aList, string prefix, StringBuilder contents)
            {
                Console.WriteLine("KeepNewLine");
                string aPrefix = "";
                foreach (string each in aList)
                {
                    contents.Append(aPrefix);
                    contents.Append(each);
                    contents.Append('\n');
                    aPrefix = prefix;
                }
            }
        }
        class DropLastNewline : Strategy
        {
            public override void ToStringStrategy(List<String> list, string prefix, StringBuilder contents)
            {
                string aPrefix = "";
                string last = "";
                //List<String> list = new List<string>();
                //list.AddRange(aList);
                if (list.Count > 0)
                {
                    last = list.Last();
                    list.RemoveAt(list.Count - 1);
                }
                foreach (string each in list)
                {
                    contents.Append(aPrefix);
                    contents.Append(each);
                    contents.Append('\n');
                    aPrefix = prefix;
                }
                contents.Append(aPrefix);
                contents.Append(last);
            }
        }
    }
    class Tag
    {
        private List<Tag> childTags;
        private List<string> list;
        private StringBuilder currentBuilder;
        private ToStringStrategies.Strategy toStringStrategy;
        private static ToStringStrategies.Strategy dropStrategy=new ToStringStrategies.DropLastNewline();
        private static ToStringStrategies.Strategy keepStrategy = new ToStringStrategies.KeepNewLine();
        private string name;
        private string prefix;
        private string closingPrefix;
        private string appendage;
        private string looseTag;
        private bool childrenAreLoose;
        private bool isNested;

        private bool isParagraph;

        public bool IsParagraph
        {
            get { return isParagraph; }
            set { isParagraph = value; }
        }
        public bool IsNested
        {
            get { return isNested; }
            set { isNested = value; }
        }

        public Tag()
        {
            childTags = new List<Tag>();
            list = new List<string>();
            currentBuilder = new StringBuilder();
            toStringStrategy = dropStrategy;
            name = "p";
            prefix = "";
            closingPrefix = "";
            appendage = "\n";
            looseTag = "";
            childrenAreLoose = false;
            isNested = false;
            isParagraph = false;
        }
        public void Append(char c)
        {
            currentBuilder.Append(c);
        }
        internal void Append(string p)
        {
            currentBuilder.Append(p);
        }

        public void NewLine()
        {
            //if (currentBuilder.Length>0)
            // if (!isNested || !areChildrenLoose())
            {
                list.Add(currentBuilder.ToString());
                currentBuilder.Length=0; // = new StringBuilder();
            }
        }
        public int size()
        {
            return list.Count;
        }
        public int contentsSize()
        {
            return list.Count;
        }
        public Tag NewChildTag()
        {
            Tag tag = new Tag();
            childTags.Add(tag);
            return tag;
        }
        public void KeepNewLine()
        {
            toStringStrategy = keepStrategy;
        }


        public override string ToString()
        {
            var contents = new StringBuilder();
            toStringStrategy.ToStringStrategy(listCopy(), prefix, contents);

            // Make only list of strings into Loose
            string looseContents = renderLooseTag(contents);
            contents.Length = 0;
            contents.Append(looseContents);
            // Append childTags
            renderChildrenToLoose();
            RenderTags(contents);
            return renderHTML(contents);
        }
        private List<string> listCopy()
        {
            var aList = new List<string>();
            //if ((!isNested || !isLoose()) && currentBuilder.Length > 0)
            //{
            //    aList.Add(currentBuilder.ToString());
            //}
            aList.AddRange(list);
            return aList;
        }

        internal void RenderTags(StringBuilder contents)
        {
            foreach (Tag tag in childTags)
            {
                contents.Append(tag);
            }
        }
        private string renderHTML(StringBuilder contents)
        {
            string actualContents = contents + closingPrefix;
            string ret = prefix + "<" + name;
            if (actualContents.Length > 0)
            {
                ret += ">" + actualContents + "</" + name + ">";
            }
            else
            {
                ret += " />";
            }
            return ret + appendage;
        }
        private string renderLooseTag(StringBuilder contents)
        {
            if (looseTag.Length>0)
            {
                string app = "";
                if ((name=="li") && isNested)
                {
                    app = "\n\n";
                }
                return "<" + looseTag + ">" + contents + "</" + looseTag + ">"+app;
            }
            else
            {
                return contents.ToString();
            }
        }
        internal void postProcessText(Processor processor)
        {
            processor.postProcess(list);
            foreach (Tag item in childTags)
            {
                item.postProcessText(processor);
            }
        }
        internal void SetAppendage(string p)
        {
            appendage = p;
        }
        internal void SetTagName(string p)
        {
            name = p;
        }
        internal string getName()
        {
            return name;
        }
        internal void SetPrefix(string p)
        {
            prefix = p;
        }
        internal void SetClosingPrefix(string p)
        {
            closingPrefix = p;
        }

        internal List<string> TransferStrings()
        {
            // Remember my own strings
            List<string> ret = list;
            // Make myself a new list
            list = new List<string>();
            return ret;
        }

        internal void setToLoose()
        {
            looseTag = "p";
        }
        internal bool isLoose()
        {
            return (looseTag == "p");
        }
        internal void setChildrenToLoose()
        {
            //Console.WriteLine(name);
            childrenAreLoose = true;
        }
        internal bool areChildrenLoose()
        {
            return childrenAreLoose;
        }
        internal void renderChildrenToLoose()
        {
            if (childrenAreLoose)
            {
                foreach (Tag child in childTags)
                {
                    child.setToLoose();
                }
            }
        }

    }
}
